package com.ruoyi.common.utils;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * @author cc
 * @ClassName: com.sjsd.core.utils
 * @date: 2025/4/12 09:36
 * @Description:
 */
@Slf4j
public class ObjectMapperUtils {
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    static {
        OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }


    public static <T> T strToObject(String message, Class<T> clazz) {

        T result = null;
        try {
            result = OBJECT_MAPPER.readValue(message, clazz);
        } catch (Exception e) {
            log.warn("转化对象出错:{}", message, e);
        }
        return result;
    }

    public static <T> List<T> strListToObjectList(List<String> list, Class<T> clazz) {
        List<T> resultList = new ArrayList<>();

        for (String message : list) {
            T result;
            try {
                result = OBJECT_MAPPER.readValue(message, clazz);
                resultList.add(result);
            } catch (Exception e) {
                log.warn("转化对象出错:{}", message, e);
            }
        }

        return resultList;
    }

    public static <T> List<T> jsonToObjectList(String targetJson, Class<T> clazz) {
        List<T> resultList = new ArrayList<>();
        try {
            // 使用 TypeReference 构造泛型类型
            resultList = OBJECT_MAPPER.readValue(
                    targetJson,
                    OBJECT_MAPPER.getTypeFactory().constructCollectionType(List.class, clazz)
            );

        } catch (Exception e) {
            log.error("JSON 转换失败", e);
        }
        return resultList;
    }
}
